//
const Busboy = require('busboy');
const fs = require('fs');
const fse = require('fs-extra');
const os = require('os');
const snowflake = require('node-snowflake').Snowflake;
const path = require('path');

const UEditorConfig = global.UEditorConfig;

let upConfig,fieldName;

/**
 * 处理 FormData 上传数据（文件）
 */
function handleUploadFormData(req, res, next) {
  // 文件处理
  let busboy = new Busboy({
    headers: req.headers
  });
  // 监听file事件获取文件(字段名，文件，文件名，传输编码，mime类型)
  busboy.on('file', (fieldName, file, filename, encoding, mimetype) => {
    let tmpDir = path.join(os.tmpdir(), path.basename(filename));
    let name = snowflake.nextId() + path.extname(tmpDir);
    let dest = path.resolve('.', UEditorConfig.upBaseURL, UEditorConfig.upSaveURL, upConfig.path, name);
    // 将文件放入tempdir
    let writeStream = fse.createWriteStream(tmpDir);
    file.pipe(writeStream);
    writeStream.on('close', () => {
      // 移动到项目文件夹下
      fse.move(tmpDir, dest, (err) => {
        if(err){
          throw err;
        }
        res.json({
          state: 'SUCCESS',
          url: req.fullURL + UEditorConfig.upSaveURL + '/' + upConfig.path + name,
          title: req.body.pictitle,
          original: filename
        });
      });
    });
  });
  // 非文件字段
  busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated) => {
    console.log(fieldname + '===' + val);
  });
  // 数据处理完事件
  busboy.on('finish', () => {
  });
  // 将流链接到busboy对象
  req.pipe(busboy);
}

//
module.exports = function($upConfig, $fieldName){
  upConfig = $upConfig;
  fieldName = $fieldName
  return handleUploadFormData;
};
